﻿using log4net;
using log4net.Config;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace TimerJobServer
{
    public class LogHelp
    {
       static string LogPath = AppDomain.CurrentDomain.BaseDirectory + "log4net.config";

        public static void ConfigLog4Net()
        {
            var logCfg = new FileInfo(LogPath);
            XmlConfigurator.Configure(logCfg);
        }

        public static void Watch()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = AppDomain.CurrentDomain.BaseDirectory;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "log4net.config";

            //watcher.Filter = filter;
            watcher.Changed += new FileSystemEventHandler(OnProcess);
            watcher.EnableRaisingEvents = true;
        }

        private static void OnProcess(object sender, FileSystemEventArgs e)
        {
            try
            {
                ConfigLog4Net();
                if (_handler!=null)
                {
                    SetMinaLog(_handler);//复制监控信息
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        static MinaServerHandler _handler;

        public static void SetMinaLog(MinaServerHandler handler)
        {
            var MinaLog = GetMinaLogAppender();
            if (MinaLog!=null&&handler!=null)
            {
                _handler = handler;
                MinaLog.minaServerHandler = handler;
            }
        }

        /// <summary>
        /// 获取服务Mina日志记录器
        /// </summary>
        /// <returns></returns>
        private static MinaLogAppender GetMinaLogAppender()
        {
            try
            {
                var hierarchy = LogManager.GetRepository() as Hierarchy;
                var appenders = hierarchy.Root.Repository.GetAppenders();

                foreach (var appender in appenders)
                {
                    var uiLogAppender = appender as MinaLogAppender;
                    if (uiLogAppender != null)
                    {
                        return uiLogAppender;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return null;
        }
    }
}
